package com.kaifamiao.wendao.filter;

import org.tinylog.Logger;

import javax.servlet.*;
import java.io.IOException;
import java.nio.charset.Charset;

public class CharacterEncodingFilter implements Filter {

    public static final String DEFAULT_CHARSET = "UTF-8";
    public static final String CHARSET_INIT_PARAM_NAME = "encoding";

    private String charsetName;
    private String filterName;

    @Override
    public void init(FilterConfig config) throws ServletException {
        filterName = config.getFilterName();
        Logger.trace("初始化过滤器(name: {}, hash: {})", filterName, this.hashCode());
        charsetName = config.getInitParameter(CHARSET_INIT_PARAM_NAME);
        charsetName = charsetName == null || charsetName.isBlank() ? DEFAULT_CHARSET : charsetName;
        charsetName = Charset.isSupported(charsetName) ? charsetName : DEFAULT_CHARSET;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        Logger.trace("过滤器(name: {}, hash: {})正在执行过滤", filterName, this.hashCode());
        req.setCharacterEncoding(charsetName);
        resp.setCharacterEncoding(charsetName);
        chain.doFilter(req,resp);
    }

    @Override
    public void destroy() {
        Logger.trace("释放过滤器(name: {}, hash: {})占用的资源", filterName, this.hashCode());
    }
}
